#include "Common.glsl"


#if VERTEX
    uniform mat4 proj;
    uniform vec4 position_extent;
    
    in layout(location = POSITION) vec3 in_position;
    
    out vec4 viewPos;
    out vec4 vpos;

    void main()
    {
        viewPos = vec4(position_extent.xyz + position_extent.w*in_position, 1);
        vpos = proj * viewPos;
        gl_Position = vpos;
    }
#endif


#if FRAGMENT
    uniform vec4 nearFarPlanes; // (near, far, 1/near, 1/far)
    uniform sampler2D linearDepthTex;
    uniform sampler2D normalTex;
    uniform vec4 position_extent;
    uniform vec4 colour_radius;
    
    in vec4 viewPos;
    in vec4 vpos;
    
    out vec4 out_colour;
    
    void main()
    {
        vec2 texCoord = 0.5 + 0.5 * vpos.xy/vpos.w;
        float linearDepth = UnpackFloat(texture(linearDepthTex, texCoord));
        vec3 N = 2*texture(normalTex, texCoord).xyz - 1;
        vec3 P = nearFarPlanes.y * linearDepth * viewPos.xyz/-viewPos.z;
        vec3 L = position_extent.xyz - P;
        float Ldist = length(L);
        L /= Ldist;
        float d = max(dot(N, L), 0);
        out_colour = vec4(d*colour_radius.xyz, 1);

        out_colour.rgb *= SphereLightAttenuation(Ldist, colour_radius.w, position_extent.w);
    }
#endif
